package com.guanjialhx.controller;

import com.alibaba.fastjson.JSON;
import com.guanjialhx.pojo.Teacher;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author 邓昕劼
 * @version 1.3
 */
@RestController
@RequestMapping({"/QiXiaoData"})
public class QiXiaoDataController {

    //日志打印
    private final Logger log = LoggerFactory.getLogger(WeChatPayInfoController.class);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    /**
     * 访问启效云的参数
     */
    private static final String appKey = "d3aa45bbd1e94d70b5fe59b1fa37da21";
    private static final String appSecret = "883fbc209be344e899544af7c7caa0fc";
    private static final String qxUrl = "https://changhu.qixiaocloud.com";


//    /**
//     *  获取启效云居家管理系中的创客老师列表
//     */
//    @GetMapping("/Teacher")
//    public List<Teacher> TeacherData(){
//        try {
//            //判断是否在有效时间里面
//            String qxToken = stringRedisTemplate.opsForValue().get("token");
//            if (qxToken == null) {
//                qxToken = this.token();
//            }
//            Map<String, String> headMap = new HashMap<>();
//            Map param = new HashMap();
//            String url = "https://changhu.qixiaocloud.com/open/qx-apaas-lowcode/gj/SelectsTeacher";
//            headMap.put("Authorization", qxToken);
//            param = new HashMap();
//            String  qxAdd = QiXiaoDataController.postJsonParam(url, param, headMap);
//            net.sf.json.JSONObject qxAddJJson = net.sf.json.JSONObject.fromObject(qxAdd);
//            net.sf.json.JSONObject data = net.sf.json.JSONObject.fromObject(qxAddJJson.getString("data"));
//            String phone = data.getString("phone");
//            String sfz = data.getString("sfz");
//            String name = data.getString("name");
//            List<String> phoneList = Arrays.asList(phone.split(","));
//            List<String> sfzList = Arrays.asList(sfz.split(","));
//            List<String> nameList = Arrays.asList(name.split(","));
//            List<Teacher> TeacherDataList = new ArrayList<>();
//            for (int i = 0; i < Math.min(Math.min(phoneList.size(), sfzList.size()), nameList.size()); i++) {
//                Teacher teacher = new Teacher(nameList.get(i), sfzList.get(i), phoneList.get(i));
//                TeacherDataList.add(teacher);
//            }
//            System.out.println("TeacherDataList = " + TeacherDataList);
//            return TeacherDataList;
//
//        } catch (Exception e) {
//            e.printStackTrace();
//            return null;
//        }
//    }

    /**
     * 下面是工具方法--------------------------------------------------------------------------------------------------------------
     */

    public String DataType(String data){
        // 创建 SimpleDateFormat 对象来解析输入日期字符串
        SimpleDateFormat inputFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
        inputFormat.setTimeZone(TimeZone.getTimeZone("GMT+8")); // 设置时区以匹配输入字符串的时区
        String outputDateFormat = "yyyy-MM-dd HH:mm:ss";
        // 创建 SimpleDateFormat 对象来格式化输出日期字符串
        SimpleDateFormat outputFormat = new SimpleDateFormat(outputDateFormat);
        outputFormat.setTimeZone(TimeZone.getTimeZone("GMT+8")); // 通常输出格式不需要时区，但这里保持一致
        try {
            // 解析输入日期字符串
            java.util.Date date = inputFormat.parse(data);
            // 格式化日期为所需的输出格式
            return outputFormat.format(date);
        } catch (ParseException e) {
            e.printStackTrace();
            return null;
        }
    }




    /**
     * 生成访问启效云的token
     */
    public String token() {
        try {
            String url = qxUrl + "/open/oauth/token";
            Map<String, String> headMap = new HashMap<>();
            Map param = new HashMap();
            param.put("appKey", appKey);
            param.put("appSecret", appSecret);
            String qxLogin = null;
            qxLogin = WeChatPayInfoController.postJsonParam(url, param, headMap);
            net.sf.json.JSONObject qxLoginJson = net.sf.json.JSONObject.fromObject(qxLogin);
            String success = qxLoginJson.getString("success");
            if ("true".equals(success)) {
                net.sf.json.JSONObject qxData = net.sf.json.JSONObject.fromObject(qxLoginJson.getString("data"));
                String qxToken = qxData.getString("access_token");
                //将token存到redis设置全局有效时间 10分钟
                System.out.println("stringRedisTemplate = " + stringRedisTemplate);
                stringRedisTemplate.opsForValue().set("token", qxToken, 10, TimeUnit.MINUTES);
                return qxToken;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     *  将map数据转成json数据
     */
    public static String postJsonParam(String url, Map<String, String> param, Map<String, String> headMap) throws Exception {
        String jsonparam = mapToJSON(param);
        return doPost(url, jsonparam, headMap);
    }

    /**
     * map 转 json
     *
     * @param param
     * @return
     */
    public static String mapToJSON(Map param) {
        String json = JSON.toJSONString(param);
        return json;
    }
    /**
     * post请求（用于请求json格式的参数）
     *
     * @param url
     * @param params
     * @param headMap
     * @return
     */
    public static String doPost(String url, String params, Map<String, String> headMap) throws Exception {

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);// 创建httpPost
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        //如果headMap不为空，则需要添加接口鉴权字段
        if (headMap != null) {
            Iterator it = headMap.keySet().iterator();
            while (it.hasNext()) {
                String key = it.next().toString();
                httpPost.setHeader(key, headMap.get(key));
            }
        }
        String charSet = "UTF-8";
        StringEntity entity = new StringEntity(params, charSet);
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String jsonString = EntityUtils.toString(responseEntity, "UTF-8");
                return jsonString;
            } else {
                System.out.println("!!!!!!!!responseEntity:" + EntityUtils.toString(response.getEntity(), "UTF-8"));
                return "请求失败，服务器状态码：" + state;
            }
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 根据身份证计算出生年月
     */
    public static String getBirthDateFromIDCard(String idCardNumber) {
        // 身份证号码中出生日期的位置
        String birthDatePart = idCardNumber.substring(6, 14);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        try {
            Date birthDate = sdf.parse(birthDatePart);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(birthDate);
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH) + 1;
            int day = calendar.get(Calendar.DAY_OF_MONTH);
            return String.format("%d-%d-%d", year, month, day);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        return null;
    }
    /**
     * 根据身份证计算性别
     */
    public static String getGenderFromIDCard(String idCardNumber) {
        // 身份证号码中性别码的位置
        int genderCode = Integer.parseInt(idCardNumber.substring(16, 17));
        if (genderCode % 2 == 0) {
            return "2";
        } else {
            return "1";
        }
    }

}
